import markdown
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404

# Create your views here.
from blog.models import Articles, Category


# 定义首页
from comments.forms import CommentForm


def index(request):
    # 按文章创建时间排序
    art_list = Articles.objects.all()
    context = {'post_list': art_list}
    return render(request, 'blog/index.html', context)

#点击文章标题显示详情
def detail(request,pk):
    # get_object_or_404 方法，其作用就是当传入的 pk 对应的文章在数据库存在时，
    # 就返回对应的 文章，如果不存在，就给用户返回一个 404 错误
    article = get_object_or_404(Articles,id=pk)
    article.body = markdown.markdown(article.body,
                                  extensions=[
                                     'markdown.extensions.extra',
                                     'markdown.extensions.codehilite',
                                     'markdown.extensions.toc',
                                  ])
    form = CommentForm()
    # 获取这篇 post 下的全部评论
    comment_list = article.comment_set.all()
    # 组包
    context = {'post':article,'form': form,'comment_list': comment_list}
    return render(request,'blog/detail.html',context)

# 归档
def archives(request, year, month):
    post_list = Articles.objects.filter(created_time__year=year,
                                    created_time__month=month
                                    )
    context = {'post_list': post_list}
    return render(request, 'blog/index.html', context)

# 分类页面
def category(request, pk):

    cate = get_object_or_404(Category, id=pk)
    post_list = Articles.objects.filter(category=cate)
    context = {'post_list': post_list}
    return render(request, 'blog/index.html', context)